<?php
namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Request;

class Page extends Common
{
    // 单页列表
    public function index() {
        $data = db('page')->select();
        $this->assign('data', $data);

        return view();
    }

    // 添加/编辑单页
    public function save_page() {
        $id = input('param.id');
        if (Request::instance()->isPost()) {
            // 提交数据
            $data = [
                'title' => input('param.title'),
                'content' => input('param.content', ''),
                'make' => input('param.make', '')
            ];

            $post_image = input('param.image', '');
            if ($post_image) {
                // 如果图片有值  则获取旧图并删除
                $image = db('page')->where('id', $id)->value('image');
                if ($image) {
                    unlink('./uploads/nav/'.$image);
                }
                $data['image'] = $post_image;
            }

            if ($id > 0)  {
                $text = '编辑';
                $rs = db('page')->where('id', $id)->update($data);
                $url = url('index');
            } else {
                $text = '添加';
                $rs = db('page')->insertGetId($data);
                $url = url('save_page', 'id=' . $rs);
            }
            if ($rs)
                return json(['code' => 200, 'msg' => $text . $data['title'] . '成功！', 'url' => $url]);
            else
                return json(['code' => 0, 'msg' => $text . $data['title'] . '失败！']);
        } else {
            $page = [];
            if ($id > 0) {
                $page = db('page')->where('id', $id)->find();
            }
            $this->assign('page', $page);
            return view();
        }
    }

}
